//
//  ZJRefresh.swift
//  刷新数据
//
//  Created by 曾静 on 16/7/1.
//  Copyright © 2016年 qq. All rights reserved.
//

import UIKit


enum StateType :String{
    
    case Normal = "正常"
    case Pulling = "拖动中"
    case Updating = "刷新中"
}
private  var refreshHeight:CGFloat = 50
private  var BSCEENW:CGFloat = UIScreen.mainScreen().bounds.size.width

class ZJRefresh: UIControl {
    
    
    //枚举不能使用可选类型!!!!!
    var refreshState:StateType = .Normal{
    
        didSet{
            
            switch refreshState{
                
            case .Normal:
                desLabel.text = refreshState.rawValue
                //if的条件只能是true以及false必须使用==,拖动中回去的时候不能更改top,只有发送通知即为刷新状态的时候才能更改
                if oldValue == .Updating{
                    //将顶部的约束更改
                  UIView.animateWithDuration(0.25, animations: { () -> Void in
                      self.scrollView?.contentInset.top -= refreshHeight
                  })
                    
                }
            case .Pulling:
                desLabel.text = refreshState.rawValue
            case .Updating:
                desLabel.text = refreshState.rawValue
         
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
//                    将tableView的top更改为之前的+50
                    
                    self.scrollView?.contentInset.top += refreshHeight
                    
                    }, completion: { (_) -> Void in
                        
                        //将刷新的view移动下面来之后发送数据请求的通知,相当于之前的通知机制
                        //如果不适用kvo机制可以采用闭包的形式
                        self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
                })
                
                
            }
            
        }
    }
    
    
    //定义一个将刷新界面回复的方法
    func endRefreshing(){
        refreshState = .Normal
    }
    private var scrollView:UIScrollView?
    private lazy var desLabel:UILabel = {
        let desLab = UILabel()
        
        desLab.text = "正常"
        
        desLab.font = UIFont.systemFontOfSize(15)
        
        desLab.textColor = UIColor.whiteColor()
        
        desLab.textAlignment = .Center
        
        return desLab
        
    }()
 
    
    //子控件获取父控件的方法
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        guard let scrollView = newSuperview as? UIScrollView else{
            return
        }
        //这里获取到的父控件是继承自或本身就是UIScrollView的控制器
        self.scrollView = scrollView
        
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        
        let contentInsetTop = self.scrollView!.contentInset.top
        
        
        let contentOffSet = self.scrollView?.contentOffset.y
        //通过这个方法就可以的到监听父控件的舒心变化的值
        //正在拖动
        if self.scrollView!.dragging{
            
           
            
            //为了反之拖动的过程的过程中一直赋值,可选类型不能进行直接的运算
            if contentOffSet > -contentInsetTop - refreshHeight && refreshState == .Pulling{

                self.refreshState = .Normal
                
            }else if contentOffSet <= -contentInsetTop - refreshHeight && refreshState == .Normal{
            
                self.refreshState = .Pulling
            }
        
        }else{
            //已经松手,如果上一个状态为拖动中,将状态更改为刷新中
            if refreshState == .Pulling{
                self.refreshState = .Updating
            }
            
            
        }
        
        
    }

    //记得移除监听者
    deinit{
        
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset", context: nil)
    }
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -refreshHeight, width: BSCEENW, height: refreshHeight))
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI(){
        
        backgroundColor = UIColor.orangeColor()
        
        addSubview(desLabel)
        
        
    
        
    }
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        desLabel.frame = CGRect(x: 0, y: 0, width: BSCEENW, height: refreshHeight)
    }
    
    

}
